<template>
  <div class="xiecheng">
    <div class="admin_main_block">
      <div class="admin_main_block_top">
        <div class="admin_main_block_left">
          <div>{{ i18n('business.supplier.from') }}</div>
        </div>

        <div class="admin_main_block_right">
          <div>
            <el-button icon="Back" @click="router.go(-1)">
              {{ i18n('common.return') }}
            </el-button>
          </div>
        </div>
      </div>

      <div class="admin_form_main">
        <el-form label-width="130px" ref="formRef" :model="dataForm" :rules="dataRule">
          <el-card class="box-card" shadow="never">
            <template v-slot:header>
              <div class="clearfix">
                <span>{{ i18n('common.basic_info') }}</span>
              </div>
            </template>
            <div class="text item text-center">
              <el-row>
                <el-col :span="4">
                  <el-form-item :label="i18n('organization.detail.license')" prop="license">
                    <el-upload
                      class="avatar-uploader"
                      :action="$http.adornUrl('/file/picture')"
                      :show-file-list="false"
                      :headers="upload_headers"
                      :on-success="handleLicenseSuccess"
                      :before-upload="beforePictureUpload">
                      <img v-if="dataForm.license" :src="dataForm.license" class="avatar-upload"/>
                      <el-icon v-else class="avatar-uploader-icon"><Plus/></el-icon>
                    </el-upload>
                  </el-form-item>
                </el-col>
                <el-col :span="20">
                  <el-form-item :label="i18n('business.supplier.type')" prop="type">
                    <el-select
                      v-model="dataForm.type"
                      :placeholder="i18n('common.please_select') + i18n('business.supplier.type')" filterable clearable>
                      <el-option v-for="(v, k) in typeList" :label="v.text" :key="k" :value="v.value"></el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item :label="i18n('organization.chinese_title')" prop="organization_id">
                    <el-select v-model="dataForm.organization_id" :placeholder="$t('common.please_select') + $t('organization.chinese_title')" filterable clearable>
                      <el-option v-for="(v, k) in organizationList" :label="v.chinese_title" :key="k" :value="v.id">
                      </el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item :label="i18n('organization.tax_code')" prop="tax_code">
                    <el-input v-model="dataForm.tax_code" :placeholder="i18n('common.please_input') + i18n('organization.tax_code')" show-word-limit maxlength="32" clearable/>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.business_scope')" prop="business_scope">
                    <el-input
                      type="textarea"
                      v-model="dataForm.business_scope"
                      :rows="3"
                      show-word-limit
                      maxlength="300"
                      :placeholder="i18n('common.please_input') + i18n('business.supplier.business_scope')">
                    </el-input>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.country_id')" prop="country_id">
                    <el-select
                      v-model="dataForm.country_id"
                      @change="setAreaStatus"
                      :placeholder="i18n('common.please_select') + i18n('business.supplier.country_id')" filterable clearable>
                      <el-option v-for="(v, k) in countryList" :label="v.text" :key="k" :value="v.value"></el-option>
                    </el-select>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.area')" v-if="areaStatus">
                    <el-cascader v-model="dataForm.area" :placeholder="$t('common.please_select') + $t('business.supplier.area')" :options="areaList" :props="levelProps" clearable></el-cascader>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.detail.address')" prop="address">
                    <el-input
                      type="textarea"
                      v-model="dataForm.address"
                      :rows="3"
                      show-word-limit
                      maxlength="500"
                      :placeholder="i18n('common.please_input') + i18n('business.supplier.detail.address')">
                    </el-input>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.manager_name')" prop="manager_name">
                    <el-input
                      v-model="dataForm.manager_name"
                      :placeholder="i18n('common.please_input') + i18n('business.supplier.manager_name')" show-word-limit maxlength="12" clearable></el-input>
                  </el-form-item>

                  <el-form-item :label="i18n('business.supplier.manager_mobile')" prop="manager_mobile">
                    <el-input
                      v-model="dataForm.manager_mobile"
                      :placeholder="i18n('common.please_input') + i18n('business.supplier.manager_mobile')" show-word-limit maxlength="15" clearable></el-input>
                  </el-form-item>

                  <el-form-item :label="i18n('common.sort')" prop="sort">
                    <el-input-number v-model="dataForm.sort" :min="0">
                    </el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-card>

          <el-card class="box-card mt10" shadow="never">
            <template v-slot:header>
              <div class="clearfix">
                <span>{{ i18n('common.detail_info') }}</span>
              </div>
            </template>
            <div class="text item">
              <el-form-item :label="i18n('business.supplier.detail.mode')" prop="mode">
                <el-select
                  v-model="dataForm.mode"
                  :placeholder="i18n('common.please_select') + i18n('business.supplier.detail.mode')" filterable clearable>
                  <el-option v-for="(v, k) in modeList" :label="v.title" :key="k" :value="v.id"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item :label="i18n('business.supplier.detail.website')" prop="website">
                <el-input
                  v-model="dataForm.website"
                  :placeholder="i18n('common.please_input') + i18n('business.supplier.detail.website')" show-word-limit maxlength="100" clearable></el-input>
              </el-form-item>

              <el-form-item :label="i18n('business.supplier.detail.mobile')" prop="mobile">
                <el-input
                  v-model="dataForm.mobile"
                  :placeholder="i18n('common.please_input') + i18n('business.supplier.detail.mobile')" show-word-limit maxlength="16" clearable></el-input>
              </el-form-item>

              <el-form-item :label="i18n('business.supplier.detail.email')" prop="email">
                <el-input
                  v-model="dataForm.email"
                  :placeholder="i18n('common.please_input') + i18n('business.supplier.detail.email')" show-word-limit maxlength="64" clearable></el-input>
              </el-form-item>

              <el-form-item :label="i18n('business.supplier.detail.description')" prop="description">
                <el-input
                  type="textarea"
                  v-model="dataForm.description"
                  :rows="3"
                  show-word-limit
                  maxlength="300"
                  :placeholder="i18n('common.please_input') + i18n('business.supplier.detail.description')">
                </el-input>
              </el-form-item>
            </div>
          </el-card>

          <el-card class="box-card mt10" shadow="never">
            <div class="text item">
              <el-form-item>
                <el-button
                  type="primary"
                  @click="dataFormSubmit(formRef)">
                  {{ i18n('common.confirm') }}
                </el-button>
                <el-button @click="resetForm(formRef)">
                  {{ i18n('common.reset') }}
                </el-button>
              </el-form-item>
            </div>
          </el-card>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup name="business-supplier-apply-form">
  import { useBase } from "@/hooks/base/useBase"
  import { useForm } from "@/hooks/form/useForm"
  import { useUpload } from "@/hooks/upload/useUpload"

  const { router, query, i18n, isAuth } = useBase()

  const model = ref('business/supplier')

  const areaStatus = ref(true)
  const typeList = ref([])
  const organizationList = ref([])
  const countryList = ref([])
  const areaList = ref([])

  const modeList = ref([
    {id: 1, title: '模式一',},
    {id: 2, title: '模式二',}
  ])

  const levelProps = ref({
    label: 'title',
    value: 'id',
    children: 'children',
    checkStrictly: false
  })

  const dataForm = reactive({
    id: 0,
    organization_id: '',
    tax_code: '',
    type: '1',
    business_scope: '',
    license: '',
    manager_name: '',
    manager_mobile: '',
    country_id: '1',
    area: '',
    mode: '',
    description: '',
    website: '',
    mobile: '',
    email: '',
    address: '',
    sort: 0,
  })

  const dataRule = reactive({
    organization_id: [{
      required: true,
      message: i18n('business.supplier.rules.organization_id.require'),
      trigger: 'blur'
    }],
    manager_name: [{
      required: true,
      message: i18n('business.supplier.rules.manager_name.require'),
      trigger: 'blur'
    }],
    manager_mobile: [{
      required: true,
      message: i18n('business.supplier.rules.manager_mobile.require'),
      trigger: 'blur'
    }],
  })

  const {
    formRef,
    resetForm
  } = useForm(model.value, dataForm)

  const {
    upload_headers,
    beforePictureUpload,
  } = useUpload(dataForm, '')

  const init = (form) => {
    dataForm.id = query.id || 0

    nextTick(() => {
      form.value.resetFields()
      if (dataForm.id) {
        $http({
          url: $http.adornUrl(`/${model.value}/view/${dataForm.id}`),
          method: 'get',
          params: $http.adornParams({}),
        }).then(({ data }) => {
          if (data && data.status === 200) {
            dataForm.id = data.data.id
            dataForm.organization_id = data.data.organization_id
            dataForm.type = data.data.type.value
            dataForm.country_id = data.data.country_id
            dataForm.business_scope = data.data.business_scope
            dataForm.manager_name = data.data.manager_name
            dataForm.manager_mobile = data.data.manager_mobile
            dataForm.sort = data.data.sort
            dataForm.area = data.data.area
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/organization/data`),
              method: 'get',
              params: $http.adornParams({
                'id': dataForm.organization_id
              }),
            }).then(({ data }) => {
              if (data.data && data.status === 200) {
                dataForm.tax_code = data.data.tax_code
                dataForm.logo = data.data.logo
                dataForm.chinese_title = data.data.chinese_title
                dataForm.english_title = data.data.english_title

                if(data.data.detail) {
                  dataForm.license = data.data.detail.license
                }
              }
            })
          }
        }).then(() => {
          if (dataForm.id) {
            $http({
              url: $http.adornUrl(`/${model.value}/detail/data`),
              method: 'get',
              params: $http.adornParams({
                'supplier_id': dataForm.id
              }),
            }).then(({ data }) => {
              if (data.data && data.status === 200) {
                dataForm.mode = data.data.mode
                dataForm.description = data.data.description
                dataForm.website = data.data.website
                dataForm.mobile = data.data.mobile
                dataForm.email = data.data.email
                dataForm.address = data.data.address
              }
            })
          }
        })
      }
    })
  }

  // 表单提交
  const dataFormSubmit = (form) => {
    form.validate(async (valid, fields) => {
      if (valid) {
        $http({
          url: $http.adornUrl(`/${model.value}/apply`),
          method: 'post',
          data: $http.adornData({
            id: dataForm.id || undefined,
            type: dataForm.type,
            organization_id: dataForm.organization_id,
            tax_code: dataForm.tax_code,
            business_scope: dataForm.business_scope,
            country_id: dataForm.country_id,
            area: dataForm.area,
            manager_name: dataForm.manager_name,
            manager_mobile: dataForm.manager_mobile,
            license: dataForm.license,
            sort: dataForm.sort,
            mode: dataForm.mode,
            website: dataForm.website,
            mobile: dataForm.mobile,
            email: dataForm.email,
            description: dataForm.description,
            address: dataForm.address,
          }),
        }).then(({ data }) => {
          if (data && data.status === 200) {
            $message.success(i18n('common.handle_success'))
            router.go(-1)
          } else {
            $message.error(data.message)
          }
        })
      }
    })
  }

  const loadTypeList = () => {
    $http({
      url: $http.adornUrl('/dictionary/data'),
      method: 'get',
      params: $http.adornParams({
        title: 'supplier_type',
      }),
    }).then(({data}) => {
      if (data && data.status === 200) {
        typeList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const loadOrganizationList = () => {
    $http({
      url: $http.adornUrl('/organization/select'),
      method: 'get',
      params: $http.adornParams({
        supplier_status: 2,
      }),
    }).then(({data}) => {
      if (data && data.status === 200) {
        organizationList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const loadCountryList = () => {
    $http({
      url: $http.adornUrl('/dictionary/data'),
      method: 'get',
      params: $http.adornParams({
        title: 'country_type',
      }),
    }).then(({data}) => {
      if (data && data.status === 200) {
        countryList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const loadAreaList = () => {
    $http({
      url: $http.adornUrl('/common/area/three'),
      method: 'get',
      params: $http.adornParams({}),
    }).then(({ data }) => {
      if (data && data.status === 200) {
        areaList.value = data.data
      } else {
        $message.error(data.message)
      }
    })
  }

  const setAreaStatus = (country_id) => {
    if(1 == country_id) {
      areaStatus.value = true
    } else {
      areaStatus.value = false
    }
  }

  /**
   * 营业执照上传成功函数
   *
   * @param {[type]} res 上传结果
   * @param {[type]} file 上传文件
   * @return {[type]}
   */
  const handleLicenseSuccess = (res, file) => {
    dataForm.license = res.data
  }

  onMounted(() => {
    init(formRef)

    loadTypeList()
    loadOrganizationList()
    loadCountryList()
    loadAreaList()
  })
</script>

<style lang="scss" scoped>
  .cx-list-image {
    width: 30px;
    height: 30px;
  }
</style>
